package com.lestv.httpUtil;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import com.lestv.jsonBeans.BaseBean;
import com.lestv.jsonParser.BaseParser;

import java.util.Set;

import android.util.Log;

/**
 * java模拟浏览器发送http请求，返回json字符串	
 * @author Administrator
 *
 */
public class HttpUtils{
	
	/**
	 * 开始连接
	 * @param params
	 * @param parser
	 * @param handler
	 */
	public void startConnectNet(final HttpRequestParams params, final BaseParser parser, final NetHandler handler){
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					BaseBean baseBean = connectNetByGet(params, parser);
					if (baseBean != null) {
						handler.sendMessage(handler.obtainMessage(NetHandler.success, baseBean));
					}else{
						handler.sendEmptyMessage(NetHandler.fail);
					}
				} catch (Exception e) {
					handler.sendMessage(handler.obtainMessage(NetHandler.error, e));
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	/**
	 * 通过GET发送请求
	 * @param params
	 * @param parser
	 * @return
	 * @throws Exception
	 */
	public BaseBean connectNetByGet(HttpRequestParams params,BaseParser parser) throws Exception{
		URL url = new URL(params.getPath());
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(100000);
		conn.setReadTimeout(100000);
		conn.setRequestMethod(params.getMethod());
		conn.setUseCaches(false);//设定传送的内容类型是可序列化的Java对象
		//设置访问类型
		conn.setRequestProperty("Content-type", "application/x-java-serialized-object");
		if ("POST".equals(params.getMethod()) && params.getParams() != null) {
			conn.setDoOutput(true);//设置允许输出，用于上传图片
			String entity = getEntity(params.getParams());
			OutputStream outputStream = conn.getOutputStream();
			outputStream.write(entity.getBytes());
		}
		//判断当等于200时,200代码返回正常
		if (conn.getResponseCode() == 200) {
			String jsonStr = readInPutStream(conn.getInputStream(), params.getEncoding());
			BaseBean baseBean = (BaseBean)parser.parseObject(jsonStr);
			return  baseBean;
		}
		return null;
	}
	/**
	 * 字符串进行拼接
	 * @param map
	 * @return
	 */
	public String getEntity(Map<String, String> map){
		Set<Entry<String,String>> entrtySet = map.entrySet();
		StringBuffer sub = new StringBuffer();
		for (Entry<String, String> entry : entrtySet) {
			String key = entry.getKey();
			String value = entry.getValue();
			sub.append(key).append("=").append(value).append("&");
		}
		sub = sub.deleteCharAt(sub.length()-1);
		String entity = sub.toString();
		return entity;
	}
	
	/**
	 * 读取响应消息体字符串
	 * @param inputStream
	 * @param encoding
	 * @return
	 * @throws IOException
	 */
	public String readInPutStream(InputStream inputStream ,String encoding) throws IOException{
		ByteArrayOutputStream bo=new ByteArrayOutputStream();
		int len = 0;
		byte[] data = new byte[1024];
		while ((len=inputStream.read(data)) != -1) {
			bo.write(data,0,len);
		}
		bo.flush();
		byte[] byteArray = bo.toByteArray();
		Log.e("encoding", encoding+"----"+inputStream);
		return new String(byteArray,encoding);
	}
}
